package com.pi.shisan.component.util;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

import static java.util.concurrent.TimeUnit.NANOSECONDS;

public class SingleThreadRunner {

    private long threadId;

    private final ThreadPoolExecutor simpleThread;

    public SingleThreadRunner(String threadName) {
        simpleThread = new ThreadPoolExecutor(1, 1, 0, NANOSECONDS,
                new LinkedBlockingQueueAsBlock<>(100),r->new Thread(r, threadName));
        CountDownLatch waiter = new CountDownLatch(1);
        simpleThread.execute(()->{
            threadId = Thread.currentThread().getId();
            waiter.countDown();
        });
        while (threadId == 0L) {
            try {
                waiter.await();
            } catch (InterruptedException e) {
                Thread.yield();
            }
        }
    }

    public void execute(Runnable runnable) {
        if (simpleThread.isShutdown()) {
            return;
        }
        if (Thread.currentThread().getId() == threadId) {
            runnable.run();
            return;
        }
        try {
            simpleThread.execute(runnable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public <T>T submit(Callable<T> callable) throws Exception {
        if (simpleThread.isShutdown()) {
            return null;
        }
        if (Thread.currentThread().getId() == threadId) {
            return callable.call();
        }
        return simpleThread.submit(callable).get();
    }

    public void exit() {
        simpleThread.shutdownNow();
    }

    public boolean isShutdown() {
        return simpleThread.isShutdown();
    }

    public static class LinkedBlockingQueueAsBlock<T> extends LinkedBlockingQueue<T> {

        public LinkedBlockingQueueAsBlock(int capacity) {
            super(capacity);
        }

        @Override
        public boolean offer(T t) {
            try {
                put(t);
            } catch (InterruptedException e) {
                return false;
            }
            return true;
        }
    }

}
